#include "work.h"
#include "peripheral.h"
#include "timer.h"
#include "flash.h"
#include "temp.h"
#include "ems.h"
#include "bt.h"
#include "sc7a20.h"
#include "hf.h"
#include "adc.h"

uint8_t off_cnt,off_cnt1,off_cnt2=60,tri_cnt,s_cnt,m_cnt;
uint8_t Work_Mode=0,Work_Strength=0,Input_Voltage_State;
uint8_t Adapt_Duty,Adapt_Max_Duty,Trigger_State;
uint8_t ms10_cnt,time_cnt,Set_Count,s10_cnt;
uint16_t Input_Voltage_Under,Input_Voltage_Warning,Input_Voltage_Over;
uint16_t Set_Voltage,Set_Interval;
uint16_t Trigger_Cnt=0,Current_Voltage=0,Last_Voltage;
uint16_t debug_cnt1,off_cnt3=0;
uint8_t Last_Error=0,Error_State=0,flash_buf=0;
uint8_t debug_cnt,touch_cnt;
uint32_t Input_Voltage;
uint32_t Trigger_Count,Trigger_Error;
uint8_t low_cnt,work_cnt;
boolean_t Change_f,Trigger_last,Voltage_OK;
boolean_t Trigger_Continuous,flash_read=0;
boolean_t Trigger_OK=0,Trigger_f=0,touch_f=0;
boolean_t age_mode=0,life_mode=0,HF_f=0;
float VCC_Voltage=0;
extern uint8_t power_cnt,CAP_Temp,FAN_Temp,flash_cnt,Ems_Boost_Duty;
extern uint8_t Ems_Duty,Beep_Time,Current_Temp2,ems_pulse,touch_delay;
extern uint16_t EMS_VCC,EMS_VCCMAX_Target,ems_cnt;
extern uint32_t sum_offset;
extern boolean_t ms10_f1,ms10_f3,Touch_OK,Debug_Mode;
extern boolean_t ms10_f2,flash_f,location_f,EMS_Load;
float Charge_Current;
uint16_t ice_close_delay = 0;
const uint16_t Trigger_Pulse[2][3]={{100, 100, 100},	//4.1
									{80, 100, 335},};//60,100,335	//4.5,4.1,6.5

void Work_Driver()
{
		if(Work_Mode)
		{
				Mode_Config();
				EMS_Handler();
				// EMS_Detect();
				Trigger_Handle(Set_Interval,Set_Count);
				Trigger_Error_Detect();		
		}
		PWM_Driver(EMS_VCC_PWM_Channel,EMS_VCC_FREQ,Ems_Boost_Duty);
}	
																		
void Work_Handler()
{
		if(Work_Mode)
		{
				Touch_Detect();
				Input_Voltage_Protect();	//�����ѹ����
				Voltage_Current_Detect();
				Voltage_Control(Set_Voltage);		//���ݵ�ѹ����2s�䵽300V
		}
		if(Work_Mode==0)
		{
				Touch1_ON;
				Input_Voltage_Protect();	//�����ѹ����
				Voltage_Current_Detect();
				EMS_SW_EN_OFF;
				LED_EN_OFF;
				EMS_VCC_EN_OFF;
				GPIO_Control_Ice_OFF;
				tri_cnt=0;
				Trigger_Continuous=0;
				Voltage_OK=0;
				Adapt_Duty = 0;
				Adapt_Max_Duty = 0;
				Work_Strength=0;
				Change_f=0;
				ms10_cnt=0;
				time_cnt=0;
				Trigger_State = Trigger_End;
				Trigger_last=0;
				Ems_Boost_Duty=100;
				Ems_Duty=0;
				Set_Voltage=0;
				EMS_VCCMAX_Target=30;
		}	
		PWM_Driver(BOOST_Control_Channel,CHARGE_FREQ,Adapt_Duty);//Adapt_Duty
}

void Touch_Detect()
{
		if(ems_pulse)
		{
				Touch1_ON;
				if(Work_Mode<=2)
				EMS_SW_EN_ON;
		}
		else 		//�رչ���򿪴������
		{
		//		EMS_SW_EN_OFF;
				Touch1_OFF;
				if(touch_f==1)	//2.5ms
				{
						touch_f=0;
						touch_delay=0;
						if(age_mode==1||life_mode==1)
						{
								Touch_OK=1;
						}
						else
						{
								if(Touch2==0)
								{
										if(touch_cnt<250)
										touch_cnt++;
										if(touch_cnt>20)	//���Ӵ����˲�ʱ��
										Touch_OK=1;
								}
								else
								{
										if(Touch_OK==1)
										{
												Touch_OK=0;
												flash_cnt=0;
												flash_f=1;
										}
										touch_cnt=0;
								}
						}
				}
		}
}

void Mode_Config()	
{										
		switch(Work_Mode)
		{
			case 1:
				GPIO_Control_Ice_OFF;
				EMS_VCC_EN_ON;
				ice_close_delay = 0;
		//	EMS_SW_EN_ON;
				Trigger_Continuous=0;
				Trigger_State=Trigger_End;
				Set_Voltage=300;
				switch(Work_Strength)
				{
					case 0:EMS_VCCMAX_Target=150;break;
					case 1:EMS_VCCMAX_Target=180;break;
					case 2:EMS_VCCMAX_Target=200;break;
					default:break;
				}
				break;
			case 2:
			if(life_mode){
				if(Trigger_Continuous){
					GPIO_Control_Ice_ON;
				}
				else if(ice_close_delay > 30){
					GPIO_Control_Ice_OFF;
				}
			}
			else{
				if(ice_close_delay < 30){
					GPIO_Control_Ice_ON;
				}
				else{
					GPIO_Control_Ice_OFF;
				}
			}
				
				EMS_VCC_EN_ON;
		//	EMS_SW_EN_ON;
				switch(Work_Strength)
				{
					case 0:Set_Voltage=300;Set_Interval=220;Set_Count=5;break;
					case 1:Set_Voltage=300;Set_Interval=220;Set_Count=5;break;
					case 2:Set_Voltage=300;Set_Interval=220;Set_Count=5;break;
					default:break;
				}
				break;
			case 3:
				if(life_mode){
					if(Trigger_Continuous){
						GPIO_Control_Ice_ON;
					}
					else if(ice_close_delay > 60){
						GPIO_Control_Ice_OFF;
					}
				}
				else{
					if(ice_close_delay < 60){
						GPIO_Control_Ice_ON;
					}
					else{
						GPIO_Control_Ice_OFF;
					}
				}
				EMS_VCC_EN_OFF;
		//	EMS_SW_EN_OFF;
				EMS_VCCMAX_Target=0;
				switch(Work_Strength)
				{
					case 0:Set_Voltage=300;Set_Interval=150;Set_Count=8;break;
					case 1:Set_Voltage=300;Set_Interval=220;Set_Count=5;break;
					case 2:Set_Voltage=300;Set_Interval=500;Set_Count=2;break;
					default:break;
				}
				break;
			default:break;
		}
}

/**********************************************************
 * 10ms 调用一次
 * 功能： 打光处理
 * 
 * ******************************************/
void Trigger_Handle(uint16_t duty,uint8_t count)	//出光触发处理
{
		uint32_t i=0;
		uint16_t max_cnt=0;
		if(Trigger_Continuous==1)	//连闪中断后条件满足立即触发
		{
				if(Touch_OK==1&&Voltage_OK==1)
				{
						if(Trigger_State==Trigger_End)
						{
								Trigger_State=Trigger_Start;
								Trigger_OK=1;
								ms10_cnt=0;
						}
				}
		}
		if(Trigger_State==Trigger_Start)	//触发状态开始
		{	
				if(Trigger_OK==1)
				{
						if(Touch_OK==1&&Voltage_OK==1&&Error_State==0)
						{	
						//		printf("Cap voltage: %d\r\n",Current_Voltage);
						//		printf("VCC: %.2f\r\n",VCC_Voltage);
								off_cnt1=0;
								PWM_Driver(BOOST_Control_Channel,CHARGE_FREQ,0);			//关闭升压
								Adapt_Duty = 0;				    //下次升压占空比 初始占空比调小
								Bt_ClearIntFlag(TIM0,BtUevIrq); // 中断标志清0
								Bt_M23_Stop(TIM0);		        // 关闭定时中断
								Bt_Mode23_DisableIrq(TIM0,BtUevIrq);
								GPIO_IPL_ON;						//触发
								delay10us(Trigger_Pulse[Work_Mode-2][Work_Strength]/12);
								GPIO_IPL_OFF;
								Bt_M23_Run(TIM0);
								Bt_Mode23_EnableIrq(TIM0,BtUevIrq);
								Trigger_last = 1;
								if(Trigger_Count<500000)
								Trigger_Count++;
								Trigger_Cnt++;
								if(Trigger_Continuous==1)		
								{
										if(age_mode){
											if(Trigger_Cnt == 200){
												// Work_Mode = 3;
												Work_Strength = 1;
											}
											else if(Trigger_Cnt == 400){
												// Work_Mode = 3;
												Work_Strength = 0;
											}
											else if(Trigger_Cnt >= 500){
													// 停止
												Trigger_Continuous = 0;
												Trigger_State = Trigger_End;
												Work_Mode = 0;
												Trigger_Cnt = 0;
												printf("Work_Mode == 0, age_mode \r\n");
											}

										}
										else if (life_mode){
													//	// 寿命测试在下面定时关机里面完成
												if(Trigger_Cnt == 200){
													// Work_Mode = 3;
													Work_Strength = 1;
												}
												else if(Trigger_Cnt == 400){
													// Work_Mode = 3;
													Work_Strength = 2;
												}
												else if(Trigger_Cnt >= 500){
														// 停止
													Trigger_Continuous = 0;
													Trigger_State = Trigger_End;
													
													Trigger_Cnt = 0;
													// Work_Mode = 3;
													Work_Strength = 0;
													printf("Work_Mode == 0, life_mode \r\n");
												}
												
										}
										else
										{
												if(Work_Mode==3)//根据PRD, 模式3连闪模式，打完150发后退出
												{
														switch(Work_Strength)
														{
															case 0:max_cnt=150;break;
															case 1:max_cnt=150;break;
															case 2:max_cnt=150;break;
															default:break;
														}
														if(Trigger_Cnt>=max_cnt)
														{											
																Trigger_Continuous=0;
																Trigger_State=Trigger_End;
														}
												}
												else 
												{
														// if(Trigger_Cnt>=count*300)	//根据PRD, 模式2连闪模式，程序5min后退出 60*5 == 300
														// 220ms---1次
														// 60s --x , x ==60000/220 

														if(Trigger_Cnt>=(5*60*1000/duty))
														{											
																Trigger_Continuous=0;
																Trigger_State=Trigger_End;
														}
												}
										}
								}
								else
								{
									// printf("Trigger_Cnt:%d, max_cnt:[%d]\r\n",Trigger_Cnt, count);
										if(Trigger_Cnt>=count)	//单闪模式，退出打光
										{
												Trigger_Cnt=0;
												Trigger_State=Trigger_End;
										}
								}
								Trigger_OK=0;
						//		ms10_cnt=0;
						}	
						else
						{
								if(Trigger_Continuous==1)
								{
										Trigger_State=Trigger_End;	//方便下次，触摸立即出光
								}
								else
								{
										if(Touch_OK==0)		//由于触摸离开，则计数退出
										Trigger_Cnt++;
										if(Trigger_Cnt>=count)	// 单闪退出
										{
												Trigger_Cnt=0;
												Trigger_State=Trigger_End;
										}
								}
						}
				}
		}
		ms10_cnt++;
		if(ms10_cnt>(duty/10))
		{
				ms10_cnt=0;
				Trigger_OK=1;
		}
}

void Trigger_Error_Detect()
{
		if(Trigger_last==1)	//�ոմ���
		{
				tri_cnt++;
				if(tri_cnt>2)	//20ms
				{
						if(Current_Voltage<Last_Voltage)
						{
								if((Last_Voltage-Current_Voltage)>4)	//�е�ѹ����������ɹ�
								{
										
								}
								else
								{
										if(Trigger_Error<500000)
										Trigger_Error++;
								}
						}
						else
						{
								if(Trigger_Error<500000)
								Trigger_Error++;
						}
						tri_cnt=0;
						Trigger_last=0;
						GPIO_IPL_OFF;			//������رմ���
				}
		}
}

void Voltage_Current_Detect()
{
		uint32_t AD_Result;
		AD_Result=ADC_Convert(ADC_300V_Channel);
		Current_Voltage = AD_Result*154.0*25/10/4096;
//		AD_Result=ADC_Convert(ISET_Channel);
//		Charge_Current = AD_Result/4096.0f*2.5/0.05;
		M0P_ADC->CR0_f.BUF=1;
		AD_Result=ADC_Convert(VCC_Channel);
		VCC_Voltage=AD_Result*2.5*3/4096;
		M0P_ADC->CR0_f.BUF=0;
}

void Voltage_Control(uint16_t Target_Voltage)
{		
		if(Trigger_last==0)	 //记录触发前的电压
		Last_Voltage=Current_Voltage;
		if(Current_Voltage>360)
		{
				Error_State|=CHARGE_SPEED_ERROR;
				Work_Mode=0;
		}
		if(Current_Voltage>(Target_Voltage+Voltage_Offset))	 //电压偏高，开启放电
		{
				Voltage_OK=1;
				Adapt_Duty=0;
		}
		else if(Current_Voltage>(Target_Voltage-Voltage_Offset)) //电压OK，占空比维持最小
		{
		//		LED8_ON;
				Voltage_OK=1;
//				if(Adapt_Max_Duty<15)
//				Adapt_Duty=15;
//				else
//				Adapt_Duty=Adapt_Max_Duty-5;	//�´ο�����ѹֱ�Ӹ�ֵ
//				if(Adapt_Duty>1)
//				Adapt_Duty--;
				Adapt_Duty=0;
		}
		else 
		{
				if(Current_Voltage<(Target_Voltage-Voltage_Offset-3)) //避免电压波动导致触发失败
				{
						Voltage_OK=0;
				//		LED8_OFF;
				}
				if(Input_Voltage_State==Voltage_Normal)	//输入电压正常，则自适应占空比增加
				{
				//		if(Charge_Current<MAX_Current-0.3)
						{
								if(Adapt_Duty<MAX_Duty)
								Adapt_Duty++;
								if(Current_Voltage>150&&Voltage_OK==0)
								{
										if(Adapt_Duty<(Adapt_Max_Duty-5))
										Adapt_Duty=Adapt_Max_Duty-5;	//下次开启升压直接赋值
								}
						}
//						else if(Charge_Current>MAX_Current)
//						{
//								if(Adapt_Duty>MIN_Duty)
//								Adapt_Duty--;
//						}
						if(Adapt_Max_Duty<Adapt_Duty)	//记录稳定时的占空比
						Adapt_Max_Duty=Adapt_Duty;
				}
				else if(Input_Voltage_State==Voltage_Under)	//输入电压偏低，则自适应占空比减少
				{
						if(Adapt_Duty>MIN_Duty)
						Adapt_Duty--;
				}
		}
		if(ms10_f3==1)
		{
				ms10_f3=0;
				if(Current_Voltage<100)	
				{
						if(time_cnt<250)		
						{
								time_cnt++;
						}
						else
						{
								Error_State|=CHARGE_SPEED_ERROR;	//电容电压低于100V时间超过2.5s判断为异常，停止充电
								Work_Mode=0;
						}
				}
				else
				{
						time_cnt=0;
				}
		}
		if(Current_Voltage<150)
		{
				if(Adapt_Duty>15)
				Adapt_Duty=15;
		}
		if(Trigger_last==1)	//触发过程关闭充电
		Adapt_Duty=0;
		if(Error_State&CHARGE_SPEED_ERROR)
		{
				Adapt_Duty = 0;
		}
}

void Input_Voltage_Protect()	//�����ѹ����
{
		uint32_t AD_Result;
		AD_Result = (uint32_t)ADC_Convert(ADC_24V_Channel);
		Input_Voltage = AD_Result*110.0*25/10/4096;
		if(Input_Voltage>Input_Voltage_Over)
		{
				Input_Voltage_State=Voltage_Over;		//3
		}
		else if(Input_Voltage<Input_Voltage_Under)
		{
				Input_Voltage_State=Voltage_Under;		//0
		}
		else if(Input_Voltage<Input_Voltage_Warning)	
		{
				Input_Voltage_State=Voltage_Warning;	//1
		}
		else
		{
				Input_Voltage_State=Voltage_Normal;	//2
		}
		if(Input_Voltage<215||Input_Voltage>255)
		{
				if(ms10_f2)
				{
						ms10_f2=0;
						low_cnt++;
						if(low_cnt>40)
						{
								low_cnt=0;
								if((Error_State&INPUT_ERROR)==0)
								{
										Error_State|=INPUT_ERROR;
										flash_cnt=0;
										flash_f=0;
								}
								if(Work_Mode)
								{
										Work_Mode=0;
								}
						}
				}
		}
		else if(Input_Voltage>220||Input_Voltage<250)
		{
				low_cnt=0;
				Error_State&=~INPUT_ERROR;
		}
}

/***********************************
 * 10ms调用一次
 * 
***********************************/
void Work_CountTime()	//������ʱ
{
	if(flash_read==0){
		Trigger_Count=*(__IO uint32_t *)0xFF00;
		if(Trigger_Count==-1){
			Trigger_Count=0;
		}
		Trigger_Error=*(__IO uint32_t *)0xFF10;
		if(Trigger_Error==-1){
			Trigger_Error=0;
		}
		Last_Error=*(__IO uint32_t *)0xFF20;
		flash_read=1;
	}
	off_cnt++;
	if(off_cnt > 99)	//99
	{
		off_cnt=0;
		if(Input_Voltage > 230){
			Bt_ClearIntFlag(TIM0,BtUevIrq); //�жϱ�־����
			Bt_M23_Stop(TIM0);		//�رն�ʱ�ж�
			Flash_LockSet(1<<31);
			while(Ok != Flash_OpModeConfig(FlashSectorEraseMode)){};
			while(Ok != Flash_SectorErase(0xFF00)){while(1);};
			while(Ok != Flash_OpModeConfig(FlashWriteMode)){};	
			if(Ok != Flash_Write32(0xFF00, &Trigger_Count, 1)){while(1);};
			if(Ok != Flash_Write32(0xFF10, &Trigger_Error, 1)){while(1);};
			flash_buf|=Error_State;
			if(Ok != Flash_Write8(0xFF20, &flash_buf, 1)){while(1);};
			while(Ok != Flash_OpModeConfig(FlashReadMode)){};
			while(Ok != Flash_LockAll());
			Bt_M23_Run(TIM0);
		}

		if(Work_Mode){
			//无任何操作【无按键，打光，tp】  倒计时3min后，关机（寿命测试除外）
			off_cnt1 ++;
			if(off_cnt1 > 179){
				off_cnt1 = 0;
				if(life_mode == 0){
					Work_Mode = 0;
					Beep_Time = 3;
				}
			}
			// 贴肤检测，连闪状态下离开皮肤10秒之后，退出连闪
			if((Trigger_Continuous == 1) && (Touch_OK == 0)){
				s10_cnt++;
			}
			else{
				s10_cnt = 0;
			}
			//10s
			if(s10_cnt>9){
				s10_cnt = 0;
				Trigger_Continuous = 0;
				Beep_Time = 1;
			}
			// 非寿命测试模式下，延迟1min关闭ice
			if(life_mode == 0){
				if(Touch_OK == 0){
					ice_close_delay ++;	
				}
				else{
					ice_close_delay = 0;	
				}
			}

			s_cnt++;
			if(s_cnt>59){
				s_cnt=0;
				m_cnt++;
				if(m_cnt>29)	//30min ,持续运行30min后，会强制关机【寿命测试模式除外】
				{
					m_cnt=0;
					if(life_mode == 0){
						Work_Mode=0;
						Beep_Time=3;
					}
				}
			}
			if(age_mode==1||life_mode==1){
				s_cnt = 0;		// 1秒执行一次
				off_cnt1 = 0;

				if(life_mode){
					if(Trigger_Continuous){
						off_cnt3 = 0;
					}

					off_cnt3 ++;
					ice_close_delay = off_cnt3;
					if(off_cnt3 > 60*2)	//600
					{	// 休息 n min，继续循环开始
						off_cnt3 = 0;
						Trigger_Continuous = 1;
						Trigger_State=Trigger_Start;
						
					}
				}
				else{
					off_cnt3 = 0;
				}
			}
			off_cnt2=0;
			if((Error_State&FAN_ERROR)==0)
			PWM_Driver(FAN_Channel,FAN_FREQ,100);
		}
		else
		{
				if(Touch_OK){
					Touch_OK = 0;	// 不拔电源，开机时，防止灯头led亮起一下（上次的touch_ok flag清0）
					touch_cnt = 0;
				}
				s10_cnt=0;
				s_cnt=0;
				m_cnt=0;
				off_cnt1=0;
				if(off_cnt2<30)
				{
						off_cnt2++;
						if((Error_State&FAN_ERROR)==0)
						PWM_Driver(FAN_Channel,FAN_FREQ,50);
				}
				else
				{
						PWM_Driver(FAN_Channel,FAN_FREQ,0);
				}
		}
		}
}

void DEBUG_Handler()
{
		if(Debug_Mode==1)
		{
				debug_cnt++;
				if(debug_cnt>25)	//25
				{
						debug_cnt=0;
						printf("Trigger_Count: %d\r\n",Trigger_Count);
						printf("Trigger_Error: %d\r\n",Trigger_Error);
						printf("Work_Mode: %d\r\n",Work_Mode);
						printf("Work_Strength: %d\r\n",Work_Strength);
						printf("Trigger_Continuous: %d\r\n",Trigger_Continuous);
						printf("Input voltage: %d\r\n",Input_Voltage);
						printf("Input_State: %d\r\n",Input_Voltage_State);
						printf("Cap voltage: %d\r\n",Current_Voltage);
						printf("Charge_Current: %.2f\r\n",Charge_Current);
						printf("Voltage_OK: %d\r\n",Voltage_OK);
						printf("Touch_OK: %d\r\n",Touch_OK);
						printf("CHARGE_FREQ: %d\r\n",CHARGE_FREQ);
						printf("Adapt_Duty: %d\r\n",Adapt_Duty);
						printf("CAP_Temp: %d FAN_Temp: %d\r\n",CAP_Temp,FAN_Temp);
						printf("EMS_VCC: %d\r\n",EMS_VCC);
						printf("VCC: %.2f\r\n",VCC_Voltage);
				//		printf("sum_offset:%d Location_f: %d\r\n",sum_offset,location_f);
						// printf("EMS_Load: %d\r\n",EMS_Load);
						printf("Error_State: %d\r\n",Error_State);	//1=TEMP��2=NTC��4=INPUT��8=FAN��16=CHARGE_SPEED��32=OVER_CURRENT��64=EMSV��128=GSENSOR
						printf("Last Error: %d\r\n",Last_Error);
						printf("V0.2.2\r\n");		//修改次数1.2s/8发，修改2档速度1.1s/5发,增加VCC检测
													// v0.1.8版本，修正了连闪模式1min以上，切回单打后，第一次只能打1发
													// v0.1.9 修正模式连闪5min
													// v0.2.0 屏蔽ntc风扇，（因为ntc）
													// v0.2.1 屏蔽ems负载检测，以tp检测作为ems输出控制
													// v0.2.2 ice制冷不要一直开
						debug_cnt1++;
						if(debug_cnt1>6000)	//10min
						{
								debug_cnt1=0;
								Debug_Mode=0;
								printf("Debug Mode OFF\r\n");
						}
				}
		}
}

